<?php

class UserController extends Controller
{
	/**
	 * @var string the default layout for the views. Defaults to '//layouts/column2', meaning
	 * using two-column layout. See 'protected/views/layouts/column2.php'.
	 */
	public $layout='//layouts/column2_yellow';

	/**
	 * @return array action filters
	 */
	public function filters()
	{
		return array(
			'accessControl', // perform access control for CRUD operations
			'postOnly + delete', // we only allow deletion via POST request
		);
	}

	/**
	 * Specifies the access control rules.
	 * This method is used by the 'accessControl' filter.
	 * @return array access control rules
	 */
	public function accessRules()
	{
		return array(
			array('allow',  // allow all users to perform 'index' and 'view' actions
				'actions'=>array('index','view'),
				'users'=>array('*'),
			),
			array('allow', // allow authenticated user to perform 'create' and 'update' actions
				'actions'=>array('create','update', 'getCourseForUser', 'insertAdvisorEmail', 'deleteUserFromCourse', 'addUserToCourse', 'viewInvoiceAddresses', 'info', 'deleteInfo'),
				'users'=>array('@'),
			),
			array('allow', // allow admin user to perform 'admin' and 'delete' actions
				'actions'=>array('admin','delete'),
				'users'=>array('admin'),
			),
			array('deny',  // deny all users
				'users'=>array('*'),
			),
		);
	}

	/**
	 * Displays a particular model.
	 * @param integer $id the ID of the model to be displayed
	 */
	public function actionView($id)
	{
		$this->render('view',array(
			'model'=>$this->loadModel($id),
		));
	}
        
        protected function createInvoiceAddressesForUser($user_id) {
            
            $invoicesCount = 2;
            $types = array('AMS', 'FAB', 'Firma', 'Sonstige');
            
            for ($i = 0; $i < $invoicesCount; $i++) {
                $invoiceAddress = new InvoiceAddress;
                $invoiceAddress->user_id = $user_id;
                $invoiceAddress->type = $types[$i];
                $invoiceAddress->save();
            }
            
        }
        
        private function getInternalNumber($lastName) {

            $first_char = $lastName[0];
            
            if (strtolower($first_char) === 's') {
                if (strtolower($lastName[1]) === 'c' && strtolower($lastName[2]) === 'h') {
                    $first_char = 'SCH';
                } else if (strtolower($lastName[1] === 't')) {
                    $first_char = 'ST';
                }
            }
            
            $criteria = new CDbCriteria;
            $criteria->select = 'number';  
            $criteria->condition = 'name=:name';
            $criteria->params = array(':name'=>  strtoupper($first_char));

            $internal_nr = InternalNr::model()->find($criteria);
          
            return $internal_nr->number;
        }

	/**
	 * Creates a new model.
	 * If creation is successful, the browser will be redirected to the 'view' page.
	 */
	public function actionCreate()
	{
            
                Yii::import('ext.multimodelform.MultiModelForm');
            
		$model=new User;
                
                $invoiceAddress = new InvoiceAddress;
                $validatedMembers = array();
                
		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);

		if(isset($_POST['User']))
		{
			$model->attributes=$_POST['User'];
                        
                        $last_name = $_POST['User']['last_name'];
                        $model->internal_nr = $this->getInternalNumber($last_name);

                        date_default_timezone_set('Europe/Amsterdam');
                        $model->recorded_at = date('Y-m-d H:i:s');
                        
                        $birthday = str_replace('.', '', $model->birthday);
                        $model->social_security_nr = $_POST['User']['social_security_nr'] . ' ' . $birthday;
                        
                        if (MultiModelForm::validate($invoiceAddress, $validatedMembers, $deleteItems) && $model->save()) {
                            $masterValues = array('user_id'=>$model->user_id);
                            
                            $invoiceAddressAMS = new InvoiceAddress;
                            $invoiceAddressAMS->user_id = $model->user_id;
                            $invoiceAddressAMS->type = 'AMS';
                            $invoiceAddressAMS->save();
                            
                            $invoiceAddressFAB = new InvoiceAddress;
                            $invoiceAddressFAB->user_id = $model->user_id;
                            $invoiceAddressFAB->type = 'FAB';
                            $invoiceAddressFAB->save();

                            $invoiceAddressCompany = new InvoiceAddress;
                            $invoiceAddressCompany->user_id = $model->user_id;
                            $invoiceAddressCompany->type = 'Firma';
                            $invoiceAddressCompany->save();
                            
                            $invoiceAddressOther = new InvoiceAddress;
                            $invoiceAddressOther->user_id = $model->user_id;
                            $invoiceAddressOther->type = 'Sonstige';
                            $invoiceAddressOther->save();
                            
                            if (MultiModelForm::save($invoiceAddress, $validatedMembers, $deleteMembers, $masterValues)) {
                                
                                $this->redirect('update/'.$model->user_id,array(
                                        'model'=>$model, 'invoiceAddress'=>$invoiceAddress, 'validatedMembers'=>$validatedMembers
                                ));
                            }
                        }
		}

		$this->render('create',array(
			'model'=>$model, 'invoiceAddress'=>$invoiceAddress, 'validatedMembers'=>$validatedMembers
		));
	}

	/**
	 * Updates a particular model.
	 * If update is successful, the browser will be redirected to the 'view' page.
	 * @param integer $id the ID of the model to be updated
	 */
	public function actionUpdate($id)
	{
            
                Yii::import('ext.multimodelform.MultiModelForm');
            
		$model=$this->loadModel($id);
                
                $invoiceAddress = new InvoiceAddress;
                $validatedMembers = array();

		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);

		if(isset($_POST['User']))
		{
			$model->attributes=$_POST['User'];
                        
                        $masterValues = array('user_id'=>$model->user_id);
                        
                        if (MultiModelForm::save($invoiceAddress, $validatedMembers, $deleteMembers, $masterValues) && $model->save()) {
                            $this->redirect($this->createUrl('user/update',array('id'=>$id)));
                        }
		}

		$this->render('update',array(
			'model'=>$model, 'invoiceAddress'=>$invoiceAddress, 'validatedMembers'=>$validatedMembers
		));
	}

	/**
	 * Deletes a particular model.
	 * If deletion is successful, the browser will be redirected to the 'admin' page.
	 * @param integer $id the ID of the model to be deleted
	 */
	public function actionDelete($id)
	{
            
                // delete all invoice addresses
                $criteria = new CDbCriteria;
                $criteria->condition = 'user_id=:user_id';
                $criteria->params = array(':user_id'=>$id);
                
                InvoiceAddress::model()->deleteAll($criteria);
                
                // delete all course_takens
                CourseTaken::model()->deleteAll($criteria);
            
		$this->loadModel($id)->delete();

		// if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
		if(!isset($_GET['ajax']))
			$this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin'));
	}

	/**
	 * Lists all models.
	 */
	public function actionIndex()
	{
		$dataProvider=new CActiveDataProvider('User');
		$this->render('index',array(
			'dataProvider'=>$dataProvider,
		));
	}

	/**
	 * Manages all models.
	 */
	public function actionAdmin()
	{
		$model=new User('search');
		$model->unsetAttributes();  // clear any default values
		if(isset($_GET['User']))
			$model->attributes=$_GET['User'];

		$this->render('admin',array(
			'model'=>$model,
		));
	}

	/**
	 * Returns the data model based on the primary key given in the GET variable.
	 * If the data model is not found, an HTTP exception will be raised.
	 * @param integer $id the ID of the model to be loaded
	 * @return User the loaded model
	 * @throws CHttpException
	 */
	public function loadModel($id)
	{
		$model=User::model()->findByPk($id);
		if($model===null)
			throw new CHttpException(404,'The requested page does not exist.');
		return $model;
	}

	/**
	 * Performs the AJAX validation.
	 * @param User $model the model to be validated
	 */
	protected function performAjaxValidation($model)
	{
		if(isset($_POST['ajax']) && $_POST['ajax']==='user-form')
		{
			echo CActiveForm::validate($model);
			Yii::app()->end();
		}
	}
        
        
    protected function modelToArray($model) {
	
/* 		$centrals = Central::model()->findAll(); */
		
		$modelArray = array();
		
		foreach($model as $m) {
			$modelArray[$m->id] = $m->name;
		}
		
		return $modelArray;
	}
        
                
    protected function advisorArray($model) {
	
/* 		$centrals = Central::model()->findAll(); */
		
		$modelArray = array();
		
		foreach($model as $m) {
			$modelArray[$m->advisor_id] = $m->last_name . ", " . $m->first_name;
		}
		
		return $modelArray;
	}
	
	protected function staffArray($model) {
		
		$modelArray = array();
		
		foreach($model as $m) {
			$modelArray[$m->staff_id] = $m->first_name . " " . $m->last_name;
		}
		
		return $modelArray;		
		
	}

    public function actionGetCourseForUser($id) {
        $this->render('courses',array('user_id'=>$id,));            
    }           
        
        public function actionInsertAdvisorEmail() {
            
            if (isset($_POST['User']['advisor1'])) {
                
                $nameArray = explode(', ', $_POST['User']['advisor1']);
                $lastName = $nameArray[0];
                $firstName = $nameArray[1];
                $criteria = new CDbCriteria;
                $criteria->select='email';
                
                $conditions = array(
                    'last_name=:last_name',
                    'first_name=:first_name',
                );
                
                $criteria->condition=implode(' AND ',$conditions);

                $criteria->params=array(':last_name'=>$lastName, ':first_name'=>$firstName);
                
                $advisor = Advisor::model()->find($criteria);   
                
                
                echo CHtml::tag('div class="control-group"', array(), false, false);
                echo CHtml::tag('label class="control-label" for="User_advisor_email"', array(), false, false);
                echo("AMS/FAB Betreuer Email </label>");
                echo CHtml::tag('div class="controls"', array(), false, false);
                echo CHtml::tag('input id="User_advisor_email" type="text" maxlength="100" name="User[advisor_email]"', array('value'=>$advisor->email));
                echo("</input></div></div>");
            }

        }
        
        private function deleteUserFromSubmodules($user_id, $course_id) {
            $course = Course::model()->findByPk($course_id);
            
            if (count($course->children) > 0) {
                // delete user from all submodules
                foreach($course->children as $submodule) {
                    
                    $conditions = array(
                        'course_id=:course_id',
                        'user_id=:user_id',
                    );

                     $params = array(':course_id' => $submodule->course_id,
                                     ':user_id' => $user_id);
                     $condition=implode(' AND ',$conditions);
                    
                     CourseTaken::model()->deleteAll($condition, $params);
                }
            }
        }
        
        public function actionDeleteUserFromCourse($course_id, $user_id) {
            
            $this->deleteUserFromSubmodules($user_id, $course_id);
            
            $conditions = array(
                'course_id=:course_id',
                'user_id=:user_id',
            );
             
             $params = array(':course_id' => $course_id,
                             ':user_id' => $user_id);
             $condition=implode(' AND ',$conditions);
             
            if (CourseTaken::model()->deleteAll($condition, $params)) {
                $this->render('courses',array('user_id'=>$user_id));
            }
        }
        
        private function addUserToSubmodules($user_id, $course_id) {
            $course = Course::model()->findByPk($course_id);
            
            // if the course has submodules
            if (count($course->children) > 0) {
                // add User to all submodules
                foreach($course->children as $submodule) {
                    $course_taken = new CourseTaken;
                    $course_taken->user_id = $user_id;
                    $course_taken->course_id = $submodule->course_id;
                    $course_taken->save();
                }
            }
        }
        
        
        /**
         * 
         * adds the user with the id $user_id to the selected course with the id $course_id
         * 
         * if no course is selected ($course_id == null), a view to select a course will be rendered
         *
         * @param type $course_id
         * @param type $user_id
         */
        public function actionAddUserToCourse($course_id, $user_id) {
     
            // filtering
            $model = new Course('search');
            $model->unsetAttributes();  // clear any default values
            
            if (isset($_GET['Course'])) {      
                $model->attributes=$_GET['Course'];
            }
            
            if ($course_id == null) {
                // no course has been selected --> render the view to select a specific course
                $this->render('addUserToCourse', array('user_id'=>$user_id, 'model'=>$model, 'error'=>false));
            } else {
                // a course has been selected
                
                // check if the user has already been added to the selected course
                $conditions = array(
                    'course_id=:course_id',
                    'user_id=:user_id',
                );

                $params = array(':course_id' => $course_id,
                                ':user_id' => $user_id);
                $condition = implode(' AND ',$conditions);
 
                if (CourseTaken::model()->find($condition, $params)) {
                    // user has already been added to the selected course
                    $this->render('addUserToCourse', array('user_id'=>$user_id, 'model'=>$model, 'error'=>true));
                } else {
                    
                    // user has not been added to the selected course yet, so finally add the user
                    
                    // add the user to all submodules of the selected course
                    $this->addUserToSubmodules($user_id, $course_id);
                
                    $course_taken = new CourseTaken;
                    $course_taken->user_id = $user_id;
                    $course_taken->course_id = $course_id;

                    if ($course_taken->save()) {
                        $this->render('courses',array('user_id'=>$user_id));
                    }                    
                }
                
            }
        }
        
        public function actionViewInvoiceAddresses($user_id) {

            Yii::import('ext.multimodelform.MultiModelForm');

            $model = $this->loadModel($user_id);

            $invoiceAddress = new InvoiceAddress;
            $validatedMembers = array();

            // Uncomment the following line if AJAX validation is needed
            // $this->performAjaxValidation($model);

            if(isset($_POST['InvoiceAddress']))
            {
                    $masterValues = array('user_id'=>$model->user_id);

                    if (MultiModelForm::save($invoiceAddress, $validatedMembers, $deleteMembers, $masterValues) && $model->save()) {
                        $this->redirect($this->createUrl('user/viewInvoiceAddresses',array('user_id'=>$user_id)));
                    }
            }

            $this->render('invoice_address',array(
                    'model'=>$model, 'invoiceAddress'=>$invoiceAddress, 'validatedMembers'=>$validatedMembers
            ));
        }
        
        public function actionInfo($user_id) {

            if (isset($_POST['UserInfo'])) {
                
                $model = new UserInfo;
                
                $model->info = $_POST['UserInfo']['info'];
                
                // user who recorded the info
                $user = Staff::model()->findByPk($_POST['UserInfo']['recorded_by']);
                
                $model->recorded_by = $user->first_name . " " . $user->last_name;
                
                date_default_timezone_set('Europe/Amsterdam');
                $model->date = date('Y-m-d H:i:s');
                
                $model->user_id = $user_id;
                
                $model->save();

            }
            
            $this->render('info',array('model'=> UserInfo::model(), 'user_id'=>$user_id));
        }
        
        public function actionDeleteInfo($id, $user_id) {
            $conditions = array(
                'id=:id',
                'user_id=:user_id',
            );
             
            $params = array(':id' => $id,
                            ':user_id' => $user_id);
            $condition = implode(' AND ', $conditions);

            UserInfo::model()->deleteAll($condition, $params);

            $this->render('info',array('model'=> UserInfo::model(), 'user_id'=>$user_id));
        }

}
